package com.ithema.interceptors;

import com.ithema.utils.JwtUtil;
import com.ithema.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 拦截器
 */
@Component
public class LoginInterceptors implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        try {
            //从redis中获取token
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            String redisToken = operations.get("token");
            //验证redis中token是否已过期或者为空
            if (redisToken == null || !redisToken.equals(token)){
                throw new RuntimeException("token已失效，请重新登录");
            }
            Map<String, Object> stringObjectMap = JwtUtil.parseToken(token);
            //将解析出来的数据保存到ThreadLocal中
            ThreadLocalUtil.set(stringObjectMap);
            //放行
            return  true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除ThreadLocal中用户信息
        ThreadLocalUtil.remove();
    }
}
